import {app, BrowserWindow, globalShortcut, Menu} from 'electron'
import {fileURLToPath} from 'url'
import {dirname, join} from 'path'

const __dirname = dirname(fileURLToPath(import.meta.url))

// 屏蔽安全警告
// ectron Security Warning (Insecure Content-Security-Policy)
process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true'

let win
const createWindow = () => {
    win = new BrowserWindow({
        // 窗口图标
        icon: join(__dirname, 'public/icons/icon.ico'),
        width: 800,
        height: 850,
        resizable: false,
        maximizable: false, // 不能双击最大化
        frame: false,
        // center: true, // 窗口居中
        title: 'twinkle settings',
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
            webSecurity: false,
        },
    })
    if (process.env.VITE_DEV_SERVER_URL) {
        win.loadURL(process.env.VITE_DEV_SERVER_URL)
        // win.webContents.openDevTools();
    } else {
        win.loadFile(join(__dirname, 'dist/index.html'))
    }
    createMenu()
}

// 设置菜单栏
function createMenu() {
    // darwin表示macOS，针对macOS的设置
    if (process.platform !== 'darwin') {
        // windows及linux系统
        Menu.setApplicationMenu(null)
    }
}

app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
        createWindow()
    }
})

app.whenReady().then(() => {
    // globalShortcut.register("CommandOrControl+Shift+i", function () {
    // 隐藏菜单栏后，需要在这里注册打开 dev tools 的快捷键 。f12 注册不了，官网说不能注册其它应用已经注册了的快捷键
    globalShortcut.register('CommandOrControl+f12', function () {
        win.webContents.openDevTools()
    })
    globalShortcut.register('f4', () => {
        win.close()
    })
    createWindow()
})

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit()
})

app.on('will-quit', () => {
    // 注销快捷键
    // globalShortcut.unregister('CommandOrControl+f12')
    // 注销所有快捷键
    globalShortcut.unregisterAll()
})
